<?php
class Cms_View_Helper_Navigation
{
    public $view;
	public $acl;
	public $userRole;
	
    public function navigation($MenuName)
    {	
		$CONFIG = Zend_Registry::get('config');
		$CACHE = Zend_Registry::get('cache');
		
		if($CONFIG->application_state == 'production')
		{
			if(!$this->acl = $CACHE->load('acl'))
			{
				$this->acl = Acl::getInstance();
				$CACHE->save($this->acl,'acl');
			}
		}
		else
			$this->acl = Acl::getInstance();
	
		$auth = Zend_Auth::getInstance();
		if (!$auth->hasIdentity()) 
		{
			$this->userRole = 'guest';
		}
		else
		{
			$user = new Zend_Session_Namespace('Zend_Auth');
			$this->userRole = $user->userRole;
		}
		
		$CONFIG = Zend_Registry::get('config');
		$CACHE = Zend_Registry::get('cache');
		
		if($CONFIG->application_state == 'production')
		{
			if (!$menuItems = $CACHE->load("navigation_".$this->userRole.'_'.$MenuName))
			{
				$menuItems = $this->buildMenu($MenuName);
				$CACHE->save($menuItems, "navigation_".$this->userRole.'_'.$MenuName);
			}
		}
		else
			$menuItems = $this->buildMenu($MenuName);
		
       return $menuItems;
    }
	
	public function buildMenu($MenuName)
	{
		$menu = Doctrine::getTable('Menu')->findOneByName($MenuName);
		
		$children = $menu->getNode()->getChildren();
		$menuItems = NULL;
		foreach($children as $child)
		{
			if($child->module == "Page")
			{
				$menuItems['/page?page='.$child->controller] = $child->name;
			}
			
			$Module = $child->module;
			$Controller = !empty($child->controller)?$child->controller:'index';
			$Action = !empty($child->action)?$child->action:'index';
			
			if($this->acl->has(strtolower($Module).'_'.strtolower($Controller)))
			{
				if($this->acl->isAllowed($this->userRole,strtolower($Module).'_'.strtolower($Controller), strtolower($Action)))
				{	
					if($child->alias != '')
						$url = $this->view->cmsUrl(array(),$child->module.'_'.$child->controller.'-'.$child->action);
					else
					{
						$url = '/'.$this->lcfirst($Module);
						
						if($Controller != 'index')
						{
							$url .= '/'.$this->lcfirst($Controller);
							
							if($Action != 'index')
							{
								$url .= '/'.$this->lcfirst($Action);
							}
						}
						
						$pattern = "/(.)([A-Z])/";
						$replacement = "\\1-\\2"; 
						$url = strtolower(preg_replace($pattern,$replacement,$url));
					}
					$menuItems[$url] = $child->name;
				}
			}
		}
		
		return $menuItems;
	}

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }
	
	public function lcfirst($str) 
	{
    	return strtolower(substr($str, 0, 1)) . substr($str, 1);
	}
}
?>